package com.example.ucs_alg_node_manager.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.ucs_alg_node_manager.domain.Assemble;
import com.example.ucs_alg_node_manager.domain.Task;
import com.example.ucs_alg_node_manager.dto.TaskDTO;
import com.example.ucs_alg_node_manager.mapper.TaskMapper;
import com.example.ucs_alg_node_manager.service.AssembleService;
import com.example.ucs_alg_node_manager.service.TaskService;
import com.example.ucs_alg_node_manager.utils.RestTemplateUtil;
import com.example.ucs_alg_node_manager.utils.UcsPatterns;
import com.example.ucs_alg_node_manager.vo.ReturnVO;
import com.example.ucs_alg_node_manager.vo.SystemStatus;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
* @author 31586
* @description 针对表【ucs_task】的数据库操作Service实现
* @createDate 2024-08-29 16:05:15
*/
@Service
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task>
    implements TaskService {

    @Resource
    private RestTemplateUtil restTemplateUtil;

    @Resource
    private AssembleService assembleService;

    @Override
    public ReturnVO getTasks(Integer nodeId) {
        List<Task> list = list(Wrappers.<Task>lambdaQuery().eq(Task::getNodeId, nodeId)
                .orderByAsc(Task::getPriority)
                .orderByDesc(Task::getTs));
        return ReturnVO.ok().message("任务队列获取成功");
    }



    @Override
    public void submitTask(Integer nodeId) {

        List<Task> list = list(Wrappers.<Task>lambdaQuery().eq(Task::getNodeId, nodeId)
                .eq(Task::getStatus, "pending")
                .orderByAsc(Task::getPriority)
                .orderByDesc(Task::getTs));
        if(list.size()>0){
            Task task = list.get(0);
            // 拿到任务的数据源信息
            List<Assemble> taskSources = assembleService.list(Wrappers.<Assemble>lambdaQuery().eq(Assemble::getType, "task")
                    .eq(Assemble::getTypeId, task.getId()));
            if(taskSources.size()>0){
                List<String> sources = new ArrayList<>();
                for (Assemble taskSource : taskSources) {
                    sources.add(taskSource.getValue());
                }
                TaskDTO dto = new TaskDTO();
                dto.setId("task"+task.getId());
                dto.setTs(task.getTs().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
                dto.setSources(sources);

                SystemStatus<Map<String, Object>> result = restTemplateUtil.post(UcsPatterns.SUBMIT_URL, dto);
                if("ok".equals(result.getCode())){
                    if(Optional.ofNullable(result.getMsg().get("meta")).isPresent()){
                        task.setMeta(result.getMsg().get("meta").toString());
                    }else {
                        task.setMeta("无返回信息");
                    }
                    task.setStatus("running");
                    updateById(task);
                }
            }
        }
    }

    @Override
    public void stopTask(Integer nodeId) {
        Task task = getOne(Wrappers.<Task>lambdaQuery().eq(Task::getNodeId, nodeId)
                .eq(Task::getStatus, "running"));

        if (task==null) {
            return;
        }

        SystemStatus<String> result = restTemplateUtil.post(UcsPatterns.SKIP_URL, null);
        if("ok".equals(result.getCode())){
            task.setStatus("error");
            updateById(task);
        }
    }
}




